package com.kevis.zhunblog.service.configure;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.kevis.common.utils.cache.SelfKeyGenerate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.concurrent.TimeUnit;


//开启springCache注解缓存
@EnableCaching
@EnableConfigurationProperties(CacheProperties.class)
@Configuration
public class ZhunBlogCacheConfig extends CachingConfigurerSupport {

    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Autowired
    CacheProperties cacheProperties;

    //@Bean
    public RedisConnectionFactory redisConnectionFactory() {
        //return new LettuceConnectionFactory();
        return  redisConnectionFactory;
    }


    @Bean(name = "redisTemplate")
    @ConditionalOnMissingBean(RedisTemplate.class)
    public RedisTemplate<String, Object> redisTemplate() {
        FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);
        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
        redisTemplate.setConnectionFactory(redisConnectionFactory());

//        ParserConfig.getGlobalInstance().addAccept(AppConstant.BASE_PACKAGES);
        return redisTemplate;
    }

    /**
     * 二进制转成json 数据
     * 配置文件的配置没有用上
     *
     * @return
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {

        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //过期时间 可有可无 如果不写就是永久保存 看需求 这里是缓存一个小时
        //建议是永久保存
        config = config.entryTtl(Duration.ofHours(1));
        config = config.computePrefixWith(name -> name + ":");
        //CacheKeyPrefix.SEPARATOR = "";
        //序列化
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        //反序列化
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        //将配置文件中所有的配置都生效
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
            ;
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }

    @Bean
    public CaffeineCacheManager caffeineCacheManager() {
        // 第一种 CaffeineCacheManager
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(Caffeine.newBuilder()
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .initialCapacity(100)
                .maximumSize(10000))
        ;
        return cacheManager;
    }

    @Primary
    @Bean
    public RedisCacheManager redisCacheManager() {
        // 第二种 redis
        //初始化一个RedisCacheWriter
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory());
        //设置CacheManager的值序列化方式为json序列化
        //RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        RedisCacheConfiguration config = redisCacheConfiguration();//RedisCacheConfiguration.defaultCacheConfig();
        //序列化
        //config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        //反序列化
        //config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        //设置默认超过期时间是600秒
        //config = config.entryTtl(Duration.ofSeconds(600));
        //config = config.computePrefixWith(name ->name + ":");
        //System.out.println(config.getTtl());
        //初始化RedisCacheManager
        //return new RedisCacheManager(redisCacheWriter, config);
//        RedisCacheManager cacheManager = RedisCacheManager.create(redisConnectionFactory());
//        return cacheManager;

        RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisCacheWriter)
                .cacheDefaults(config)
                .build();
        return redisCacheManager;
    }

    /**
     * &#064;Cacheable(value  = "ca") 这个的缓存管理主要看这边返回的管理器
     *
     * @return 指定的缓存管理器
     */
    @Override
    public CacheManager cacheManager() {
        return super.cacheManager();
        //return new ConcurrentMapCacheManager();
    }

    /**
     * 自定义缓存的名字
     * @return
     */
    @Bean("selfKeyGenerate")
    public KeyGenerator selfKeyGenerate(){
        return new SelfKeyGenerate();
    }
}
